#!/usr/bin/env python

import urllib

'''
pygtrans.py

Still in development.



High level function summery:

translate(init_translate, from_lanKey, to_lanKey) -

Translate from one language to another using google translator.
Can also be used to find the language some text is written in.

get_text_lang(orig_text) - 

Gets the language of text submited as parameter.

lang_key_converter(str) - 

Given either the key or the vlaue for the dictionary languages
the coresponding key or value is returned.




Changes:
Name of modual changed.

Added lang_key_converter function.

self.version = 'Mozilla/5.0'     now in AppURLopener _init_

from_url_hex(str) now changes ' ' to '%20' and '&' to '%26' in str
and filters out "*". Previous functionality commented out. 
(This is only a temporary change. This function can obviously be improved.)

Added simple doc string to get_text_lang(orig_text)

TODO:

Take a look at BeautifulSoup. It might come in handy.
'''

class AppURLopener(urllib.FancyURLopener):
	def __init__(self, *args):
		self.version = 'Mozilla/5.0'
		apply(urllib.FancyURLopener.__init__, (self,) + args)

def to_url_hex(str):
	'''
	Converts a string to url style hex like %** 
	'''
	'''
	init_hex = str.encode('hex')
	endStr = ''
	n=0
	while n < len(init_hex):
		if n % 2 == 0:
			#n is even number
			endStr += '%'
		
		endStr += init_hex[n]
		n += 1

	return endStr
	'''
	str = str.replace('*', '')
	str = str.replace(' ', '%20')
	str = str.replace('&', '%26')
	
	return str
	
def from_url_hex(str):
	'''
	This function needs to be improved!
	Converts any \u00** hex values to normal text.
	'''
	# Replace google format for: '.
	str = str.replace('\u0026#39;', "'")
	
	n=0
	retBuff = ''
	strLen = len(str)

	while n < strLen:
		#better me!
		#construct buffer to keep range of indexes.
		if (n >= (strLen - 4)) and (str[n] != '\\'):
			retBuff += str[n]
			n += 1
		else:
			
			if str[n:n+4] == '\u00':
				
				retBuff += str[n+4:n+6].decode('hex')
				n += 5
			else:
				retBuff += str[n]
			n += 1
		
	return retBuff

def get_trans_text(str):
	'''
	Rettrives text translation from html string.
	'''

	before_constant = 'translatedText":"'
	after_constant = '"}, '

	bef,mid,aft = str.partition(before_constant)

	bef,mid,end = aft.partition(after_constant)

	#Convert all google format hex to normal text.
	return from_url_hex(bef)

def get_trans_key(str):
	'''
	Rettrives translation language key from string.
	'''

	before_constant = ',{"language":"'
	after_constant = '","isReliable"'

	bef,mid,aft = str.partition(before_constant)

	bef,mid,end = aft.partition(after_constant)
	
	#Convert all google format hex to normal text.
	return from_url_hex(bef)

def translate(init_translate, from_lanKey, to_lanKey):
	'''
	Translate from lang1 to lang2. 

	Returns: translated text as string.

	Example parameters: 
	from_lanKey = 'en'
	to_lanKey = 'fr'
	init_translate = 'hello world'
	return value == 'Bonjour le monde'
	'''

	url = 'http://www.google.com/uds/Gtranslate?callback=google.language.callbacks.id100&context=22&q=' + to_url_hex(init_translate) + '&langpair=' + from_lanKey + '%7C' + to_lanKey + '&key=notsupplied&v=1.0'
	urllib._urlopener = AppURLopener()
	ret =  urllib._urlopener.open(url).read()
	
	#Rip translated text from html.
	return get_trans_text(ret)

def get_text_lang(orig_text):
	'''
	Get's the language of orig_text.
	'''
	url = 'http://www.google.com/uds/GlangDetect?callback=google.language.callbacks.id100&context=22&q=' + to_url_hex(orig_text) + '&key=notsupplied&v=1.0'
	urllib._urlopener = AppURLopener()

	ret =  urllib._urlopener.open(url).read()
	
	return get_trans_key(ret)

def lang_key_converter(str):
	'''
	Given either the key or the vlaue for the dictionary languages
	the coresponding key or value is returned.
	
	Example usage 1:
	str = 'fr'
	Return value == 'french'
	
	Example usage 2:
	str = 'french'
	Return value == 'fr'
	'''
	
	languages = {
	'french' : 'fr',
	'german' : 'de',
	'italian' : 'it',
	'spanish' : 'es',
	'russian' : 'ru',
	'portuguese': 'pt',
	'dutch' : 'nl',
	'japanese' : 'ja',
	}
	
	if languages.has_key(str.lower()):
		return languages[str.lower()]
	else:
		for key in languages.keys():
  			if languages[key] == str.lower():
  				return key

#str = translate('ich bin john!', 'de', 'en')
#print str


